package com.rx.cxftest1.config;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器修改返回的SOAP -> SOAP-ENV
 */
public class XmlnsInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public XmlnsInterceptor(String phase) {
        super(phase);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        try {
            //需要放置在根节点的命名空间
            Map<String, String> envMap = new HashMap<>();
            envMap.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");

            //在命名空间下的元素都以自定义前缀生成
            Map<String, String> namespaceMap = new HashMap<>();
            namespaceMap.put("http://schemas.xmlsoap.org/soap/envelope/", "SOAP-ENV");
            JAXBDataBinding dataBinding = (JAXBDataBinding) message.getExchange().getEndpoint().getService()
                    .getDataBinding();
            dataBinding.setNamespaceMap(namespaceMap);

            message.put("soap.env.ns.map", envMap);
            //message.put("disable.outputstream.optimization", true);
            //控制输出的时候有XML头
            message.put("org.apache.cxf.stax.force-start-document", "true");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
